import axios from 'axios';
import Vue from 'vue';
import store from '../store/index';
import Router from 'vue-router';
// config =require('~/config/index')
import config from '../assets/client/config';
import {Message} from 'element-ui';
import {znk} from '../assets/util/public';
import Cookie from 'js-cookie';
import JSONBig from 'json-bigint';
axios.defaults.withCredentials = true;
axios.defaults.baseURL = config.BASE_URL;
axios.defaults.timeout = config.TIMEOUT;
axios.defaults.headers = config.HEADERS;
const instance = axios.create ({
  transformResponse: [function (data) {
    try {
      return JSONBig.parse(data)
    } catch (err) {
      return data
    }
  }]
});
Vue.use (Router);
const router = new Router ({
  mode: 'history',
});
instance.interceptors.request.use (
  param => {
    let token = param.url.indexOf ('admin/login') >= 0
      ? ''
      : param.headers.session && param.headers.session.token;
    // let token = Cookie.get('token')

    // 判断是否存在token，如果存在的话，则每个http header都加上token
    if (token) {
      param.headers.Authorization = token;
    }
    if (param.token) {
      // 临时验证
      param.headers.Authorization = param.token;
    }
    // if (!token) {
    //   window.location.href = '/login'
    // }
    return param;
  },
  error => {
    return error;
  }
);
instance.interceptors.response.use (
  response => {
    if (response.status === 200) {
      if (response.data.code !== 501) {
        if (response.data.code !== 0) {
          Message.closeAll ();
          Message ({message: response.data.msg || '请求错误！', type: 'error'});
        }
        return Promise.resolve (response);
      } else {
        // Message({ message: response.data.msg || '请求错误！', type: 'error' });
        // console.log('ppppppp',Vue)
        setTimeout (() => {
          // router.replace({path:'/login'})
          if (!process.server) {
            window.location.href = '/login';
          }
        }, 500);
        return Promise.resolve (response);
      }
    } else {
      // 这个地方可以由后台编辑状态码区分不同情况，做不同的逻辑处理
      return Promise.reject (response);
    }
    // return response
  },
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 501:
          // 返回 401 清除token信息并跳转到登录页面
          // znk.getCookie('token')
          window.location.href = '/login';
          break;
        case 506:
          // Message.error("当前操作没有权限");
          console.warn ('当前操作没有权限');
          break;
      }
    }
    return Promise.reject (error.message); // 返回接口返回的错误信息
  }
);
// 对外接口
export function $Http (method, url, params, opts = null) {
  // eslint-disable-next-line no-unused-vars
  let isdata = true;
  try {
    let methodUp = method.toUpperCase ();
    if (methodUp === 'GET' || methodUp !== 'get ') {
      isdata = false;
    } else {
      isdata = true;
    }
    const res = new Promise ((resolve, reject) => {
      const instanceOpts = {
        method: method,
        url: url,
        data: params || {},
        params: isdata ? params : null,
      };
      if (opts && opts.headers) {
        instanceOpts.headers = opts.headers;
      }

      instance (instanceOpts)
        .then (data => {
          if (data.status === 200) {
            console.log('jinlai-----',data.data)
            resolve (data.data);
          } else {
            resolve (data);
          }
        })
        .catch (err => {
          console.error ('请求接口请求异常', err);
          return Message ({message: '请求接口请求异常!' + err, type: 'error'});
        });
    }).catch (error => {
      return console.error ('接口请求异常', error);
    });

    return res;
  } catch (err) {
    // console.log('error', err.message)
    //   store.commit('LOADING', true)
  }
}
Vue.prototype.$Http = function (method, url, params) {
  return $Http (method, url, params);
};
// Vue.use($Http);
